Vue Js Watch Property: Vue js is a reactive framework, which means that it automatically updates the UI whenever the underlying data changes. However, sometimes you need to perform additional actions when a specific property changes. This is where the Vue Js watch property comes in handy. By using the Vue Js watch property, you can define a function that will be executed whenever the watched property changes. This allows you to perform complex calculations or update the UI in response to changes in your data. The watch property takes an object as its value, where each key is the property to be watched and its value is the function to be executed when the property changes
What is the purpose of using the Vue js watch property and how does it differ from computed properties?
The watch property in Vue.js allows you to watch for changes to a specific property and perform some action when that property changes. The purpose of using watch is to perform some side effect when a data property changes, such as updating the UI or calling an API.
In the code,Vue Js watch property is used to update the fullName property whenever firstName or lastName changes. This means that whenever the user types in a new value for firstName or lastName, the watch function will be triggered, which updates the fullName property with the new values.
On the other hand, computed properties are used to derive new values based on existing data properties. Computed properties are reactive and will update automatically when their dependent properties change. Computed properties are used when you want to derive a new value from existing data, and that value needs to be updated automatically when the data changes.
To summarize,Vue Js watch is used to perform a side effect when a specific data property changes, while computed properties are used to derive a new value based on existing data properties.
Vue Js Watch Property Example
<script type="module">
const app = Vue.createApp({
data() {
return {
firstName: '',
lastName: '',
fullName: ''
}
},
watch: {
firstName: function (newVal, oldVal) {
this.fullName = this.firstName + ' ' + this.lastName;
},
lastName: function (newVal, oldVal) {
this.fullName = this.firstName + ' ' + this.lastName;
}
}
});
app.mount('#app');
</script>
Output of Vue Js Watch Property



